package com.itlxd.controller;

import com.itlxd.exception.ArgsException;
import com.itlxd.global.SysMessages;
import com.itlxd.result.ResultVO;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * @author: lixiaodong
 **/
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public ResultVO upload(MultipartFile file) {
        if (null == file) {
            throw new ArgsException(SysMessages.FILE_IS_NULL);
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(path + newFileName));
        } catch (IOException e) {
            return ResultVO.error(SysMessages.FILE_UPLOAD_FAIL);
        }

        return ResultVO.success(newFileName, SysMessages.FILE_UPLOAD_SUCCESS);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            //response.setContentType("image/jpeg");
            //IOUtils.copy(fileInputStream, outputStream);

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

